<template>
  <div class="main-container">
    <div class="left_container">
      <div class="search_container">
        <div class="search_item">
          <div class="name">客户名称</div>
          <div class="input">
            <el-input
              v-model="pageData.customerName"
              clearable
              @clear="getList"
            />
          </div>
        </div>
        <div class="search_item">
          <div class="name">渠道名称</div>
          <div class="input">
            <el-input
              v-model="pageData.channelName"
              clearable
              @clear="getList"
            />
          </div>
        </div>
        <div class="search_item">
          <div class="button">
            <el-button type="search" @click.stop="getList">搜索</el-button>
          </div>
        </div>
        <div class="search_item">
          <div class="name">签订人员</div>
          <div class="input">
            <el-input v-model="pageData.signByName" clearable @clear="getList" />
          </div>
        </div>
      </div>
      <div ref="middle_container" class="middle_container">
        <el-table
          ref="table"
          :data="tableData"
          stripe
          border
          :height="tableHeight"
          style="width: 99.9%"
          highlight-current-row
          @row-click="rowClick"
          @sort-change="sortChange"
        >
          <!-- <el-table-column type="selection" width="50" /> -->
          <el-table-column prop="customerName" label="客户名称" min-width="150" />
          <el-table-column prop="channelName" label="渠道名称" min-width="150" />
          <el-table-column prop="code" label="合同单号" min-width="130" />
          <el-table-column prop="name" label="合同名称" min-width="150" />
          <el-table-column prop="signByName" label="签订人员" />
          <el-table-column prop="totalMoney" label="合同总金额" sortable="custom" min-width="120" />
          <el-table-column prop="receivedMoney" label="已回款金额" sortable="custom" min-width="120" />
          <el-table-column prop="waitReceiveMoney" label="待回款金额" sortable="custom" min-width="120" />
          <el-table-column prop="invoicedMoney" label="已开票金额" sortable="custom" min-width="120" />
          <el-table-column prop="waitInvoiceMoney" label="待开票金额" sortable="custom" min-width="120" />
          <infinite-loading
            ref="infiniteLoading"
            slot="append"
            force-use-infinite-wrapper=".el-table__body-wrapper"
            @infinite="loadNext"
          />
        </el-table>
      </div>
    </div>
    <div class="right_container">
      <div class="header_container">
        编辑开票
      </div>

      <div class="add_container">
        <div class="add_item">
          <div class="add_item_left">
            <div class="name"><label class="bitian">*</label>合同单号</div>
            <div class="show">{{ addData.code }}</div>
          </div>
          <div class="add_item_right">
            <div class="name">合同名称</div>
            <div class="show">{{ addData.name }}</div>
          </div>
        </div>
        <!-- <div class="add_item">
          <div class="name"><label class="bitian">*</label>合同名称</div>
          <div class="show">{{ addData.name }}</div>
        </div> -->

        <div class="add_item">
          <div class="add_item_left">
            <div class="name">合同总金额</div>
            <div class="show">{{ addData.totalMoney }}</div>
          </div>
          <div class="add_item_right">
            <div class="name">已回款金额</div>
            <div class="show">{{ addData.receivedMoney }}</div>
          </div>
        </div>

        <div class="add_item">
          <div class="add_item_left">
            <div class="name">已开票金额</div>
            <div class="show">{{ addData.invoicedMoney }}</div>
          </div>
          <div class="add_item_right">
            <div class="name">待开票金额</div>
            <div v-if="!addData.id" class="show" />
            <div v-else class="show">
              {{ Number(addData.totalMoney) - Number(addData.invoicedMoney) }}
            </div>
          </div>
        </div>
        <div class="add_item">
          <div class="name">待回款金额</div>
          <div v-if="!addData.id" class="show" />
          <div v-else class="show">
            {{ addData.totalMoney - addData.receivedMoney }}
          </div>
        </div>

        <el-divider />

        <div class="add_item">
          <div class="add_item_left">
            <div class="name"><label class="bitian">*</label>开票日期</div>
            <div v-if="isEdit" class="input">
              <el-date-picker
                v-model="addData.startDate"
                type="date"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="请选择"
                :editable="false"
              />
            </div>
            <div v-else class="show">{{ addData.startDate }}</div>
          </div>
          <div class="add_item_right">
            <div class="name"><label class="bitian">*</label>本次开票金额</div>
            <div v-if="isEdit" class="input">
              <el-input
                v-model="addData.thisMoney"
                clearable
                placeholder="请填写"
              />
            </div>
            <div v-else class="show">{{ addData.thisMoney }}</div>
          </div>
        </div>

        <div class="add_item">
          <div class="add_item_left">
            <div class="name"><label class="bitian">*</label>发票类型</div>
            <div v-if="isEdit" class="input">
              <div class="input">
                <el-select v-model="addData.type" clearable>
                  <el-option
                    v-for="item in billTypeOptions"
                    :key="item.id"
                    :label="item.typeName"
                    :value="item.id"
                  />
                </el-select>
                <!-- <DictSelect
                  :band-value.sync="addData.type"
                  dict-type="invoiceType"
                /> -->
              </div>
            </div>
            <div v-else class="show">{{ addData.typeName }}</div>
          </div>
          <div class="add_item_right">
            <div class="name"><label class="bitian">*</label>发票号码</div>
            <div v-if="isEdit" class="input">
              <el-input
                v-model="addData.number"
                clearable
                placeholder="请填写"
              />
            </div>
            <div v-else class="show">{{ addData.number }}</div>
          </div>
        </div>

        <div class="add_item">
          <div class="add_item_left">
            <div class="name">甲方</div>
            <div v-if="isEdit" class="input">
              <el-select v-model="addData.firstParty" clearable>
                <el-option-group
                  v-for="group in firstPartyOptions"
                  :key="group.label"
                  :label="group.label"
                  :value="group.label"
                >
                  <el-option
                    v-for="item in group.options"
                    :key="item.label"
                    :label="item.label"
                    :value="item.label"
                  />
                </el-option-group>
              </el-select>
            </div>
            <div v-else class="show">{{ addData.firstParty }}</div>
          </div>
          <div class="add_item_right">
            <div class="name">乙方</div>
            <div v-if="isEdit" class="input">

              <el-select v-model="addData.secondParty" clearable>
                <el-option
                  v-for="item in secondPartyOptions"
                  :key="item.label"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </div>
            <div v-else class="show">{{ addData.secondParty }}</div>
          </div>
        </div>
        <div class="add_item">
          <div class="name">备注</div>
          <div v-if="isEdit" class="input">
            <el-input v-model="addData.remark" clearable placeholder="请填写" />
          </div>
          <div v-else class="show">{{ addData.remark }}</div>
        </div>

        <div class="add_item">
          <div class="add_item_left">
            <div class="name">开票凭证</div>
            <div class="input">
              <FileManage
                :file-names.sync="addData.fileName"
                :file-real-names.sync="addData.fileRealName"
                style="padding-left: 20px"
                @fileName="setFileName"
              />
            </div>
          </div>
          <div class="add_item_right" />

          <!-- <div v-else>
            <FileManage
              :readonly="true"
              :file-names.sync="addData.attaName"
              :file-real-names.sync="addData.fileRealName"
              style="padding-left: 20px"
              @fileName="setFileName"
            />
          </div> -->
        </div>
      </div>

      <div ref="table_container" class="table_container">
        <el-table
          ref="table2"
          :data="tableData2"
          stripe
          border
          :height="tableHeight2"
          style="width: 99.9%"
          highlight-current-row
        >
          <el-table-column prop="startDate" min-width="150" label="开票日期" />
          <el-table-column prop="firstParty" min-width="150" label="甲方" />
          <el-table-column prop="secondParty" min-width="100" label="乙方" />
          <el-table-column prop="thisMoney" min-width="120" label="本次开票金额" />
          <el-table-column prop="typeName" label="发票类型" />
          <el-table-column prop="number" label="发票号码" min-width="100" />
          <el-table-column label="开票凭证" prop="fileName" width="170">
            <template slot-scope="scope">
              <FileManage
                v-if="scope.row.fileName"
                :readonly="true"
                :file-names.sync="scope.row.fileName"
                :file-real-names.sync="scope.row.fileRealName"
              />
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" />
          <el-table-column prop="creatByName" label="创建人员" />
          <el-table-column prop="createTime" min-width="150" label="创建时间" />
          <el-table-column label="操作" align="center" width="120">
            <template slot-scope="scope">
              <div class="button-text" @click.stop="removeItem(scope.row)">
                删除
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="button_container">
        <el-button v-if="isEdit" type="save" @click.stop="save">保存</el-button>
        <el-button v-else type="edit" @click.stop="edit">编辑</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { list, addOrUpdate, remove, getInfo } from '@/api/sale/invoicingRecord'
import { sortChange } from '@/utils/table'

export default {
  name: 'Index',
  components: {}, // 组件注册
  data() {
    return {
      pageData: {
        customerName: '',
        channelName: '',
        signByName: '',
        // id: 0,
        // reasonable: true,
        pageNum: 1,
        pageSize: 15,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      billTypeOptions: [
        { id: '1', typeName: '增值税普通发票' },
        { id: '2', typeName: '增值税专用发票' }
      ],
      addData: {
        id: '',
        code: '',
        name: '',
        totalMoney: '',
        receivedMoney: '',
        invoicedMoney: '',
        signDate: '',
        thisMoney: '',
        fileName: '',
        remark: '',
        fileRealName: '',
        type: '',
        firstParty: '',
        secondParty: '',
        number: ''
      },
      mainId: 'id',
      tableHeight: '0',
      tableHeight2: '0',
      tableData: [],
      tableData2: [],
      firstPartyOptions: [],
      secondPartyOptions: [
        { label: '无锡极联' },
        { label: '上海数易' }
      ],
      selectedRow: {},
      isEdit: true, // false:右侧区域仅为展示,true:右侧区域可编辑
      removeClick: false // 是否点了删除按钮
    }
  },

  watch: {
    'addData.fileName'() {
      if (this.addData.fileName) {
        this.addData.picUrl = this.addData.fileName
      }
    }
  },
  mounted() {
    // this.getMaterialType()
    this.$nextTick(() => {
      this.tableHeight = this.$refs.middle_container.offsetHeight

      this.tableHeight2 = this.$refs.table_container.offsetHeight
    })
  },
  methods: {
    // 排序规则改变时触发
    sortChange(column) {
      sortChange(column, this)
    },
    generateFirst(row) {
      if (row.channelName) {
        this.addData.firstParty = row.channelName
        this.firstPartyOptions = [
          {
            label: '渠道',
            options: [{
              label: row.channelName
            }]
          },
          {
            label: '客户',
            options: [{
              label: row.customerName
            }]
          }
        ]
      } else {
        this.addData.firstParty = row.customerName
        this.firstPartyOptions = [
          {
            label: '客户',
            options: [{
              label: row.customerName
            }]
          }
        ]
      }
    },
    rowClick(row, column, event) {
      // 单击选中行
      this.getInfo(row)
    },

    getList() {
      // 获取数据
      this.pageData.pageNum = 1
      this.tableData = []
      this.$refs.infiniteLoading.$emit('$InfiniteLoading:reset')
    },
    loadNext($state) {
      // 加载下一页数据
      list(this.pageData).then(res => {
        if (res.data.length > 0) {
          this.tableData = this.tableData.concat(res.data)
          this.pageData.pageNum++
          if (JSON.stringify(this.selectedRow) !== '{}') { // 如果有选中的行，恢复他的选中
            const selectedRow = this.tableData.filter(item => item.id == this.selectedRow.id)
            if (selectedRow && selectedRow.length > 0) {
              this.$refs.table.setCurrentRow(selectedRow[0])
              // 模拟点击行
              this.rowClick(selectedRow[0])
            }
          }
          $state.loaded()
        } else {
          $state.complete()
        }
      })
    },

    getInfo(row) {
      this.selectedRow = row
      getInfo(row[this.mainId]).then(res => {
        Object.keys(this.addData).forEach(key => {
          this.addData[key] = res.data[key] || (res.data[key] + '') == '0' ? res.data[key] : ''
        })
        this.tableData2 = res.data.data

        this.generateFirst(row)
        this.addData.secondParty = '无锡极联'
      })
      // this.isEdit = false // 右边输入框隐藏
    },

    edit() {
      // 编辑按钮
      if (this.addData[this.mainId] == '') {
        this.$message({
          message: '请先选择要操作的数据',
          type: 'warning'
        })
      } else {
        this.isEdit = true // 右边输入框显示出来
      }
    },

    checkForm() {
      if (!this.addData.code) {
        this.$message({
          message: '请选择合同',
          type: 'warning'
        })
        return false
      }
      if (!this.addData.startDate) {
        this.$message({
          message: '请选择开票日期',
          type: 'warning'
        })
        return false
      }
      if (!this.addData.thisMoney) {
        this.$message({
          message: '请输入本次开票金额',
          type: 'warning'
        })
        return false
      }
      if (!this.addData.type) {
        this.$message({
          message: '请选择发票类型',
          type: 'warning'
        })
        return false
      }
      if (!this.addData.number) {
        this.$message({
          message: '请输入发票号码',
          type: 'warning'
        })
        return false
      }
      const reg = /^[0-9]{8}$/
      if (!reg.test(this.addData.number)) {
        this.$message({
          message: '发票号码错误',
          type: 'warning'
        })
        return false
      }

      return true
    },
    save() {
      if (this.checkForm()) {
        const cacheData = JSON.parse(JSON.stringify(this.addData))
        cacheData.contractId = this.addData.id
        if (this.addData.type == '1') {
          cacheData.typeName = '增值税普通发票'
        }
        if (this.addData.type == '2') {
          cacheData.typeName = '增值税专用发票'
        }
        addOrUpdate(cacheData).then(res => {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.getList()
          if (!this.addData[this.mainId]) {
            Object.keys(this.addData).forEach(key => {
              this.addData[key] = ''
            })
          } else {
            this.getInfo(cacheData)
          }
        })
      }
    },

    removeItem(row) {
      this.$confirm('确定要删除吗?', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消', cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      }).then(() => {
        remove({ deleteIds: row.id }).then(res => {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.getList()
          // this.getInfo(this.selectedRow)
        })
      })
    },
    getPendingMoney(row) {
      // console.log("row",row)
      return row.totalMoney - row.receivedMoney
    },
    getTobeinvoicedMoney(row) {
      return row.totalMoney - row.invoicedMoney
    },
    setFileName(...data) {
      this.addData.fileName = data[0]
      this.addData.fileRealName = data[1]
    }
  }
}
</script>

<style lang="less" scoped>
.table_container {
  margin-top: 10px;
}

.add_item_left {
  width: 50%;
  display: flex;
}

.add_container{
  flex: unset !important;
  height: unset !important;
}
.add_item_right {
  width: 50%;
  display: flex;
}

.button-text {
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  border-color: transparent;
  color: #409eff;
  background: transparent;
  padding-left: 0;
  padding-right: 0;
}
.add_item{
  .name{
    width: 95px !important;
  }
}
</style>
